package com.bluesky.objectworld.method;

import org.apache.commons.lang3.ArrayUtils;

import com.bluesky.objectworld._Method;
import com.bluesky.objectworld._Object;
import com.bluesky.objectworld.exception.NativeMethodNotFoundException;
import com.bluesky.objectworld.exception.UnkownMessageException;

public class NativeMethod extends _Method {

	

	/**
	 * null-able
	 */
	public String nativeName;

	public NativeMethod(_Object self, String name, String nativeName) {
		super(self,name);
		
		this.nativeName = nativeName;
	}

	/**
	 * 
	 * @param obj
	 *            the method belongs to
	 */
	public NativeMethod(_Object self, String name) {
		super(self,name);

		this.nativeName = name;
	}

	@Override
	protected _Object execute(_Object[] parameters) {

		java.lang.reflect.Method method = null;
		for (java.lang.reflect.Method m : self.getClass().getMethods()) {
			if (m.getName().equals(nativeName)) {
				method = m;
				break;
			}
		}
		if (method == null)
			throw new NativeMethodNotFoundException(nativeName);
		
		Object[] parameters2 = new Object[parameters.length];
		for(int i=0;i<parameters.length;i++)
			parameters2[i] = parameters[i];
		
		try {
			
			return (_Object) method.invoke(self, parameters);
		} catch (Exception e) {

			throw new RuntimeException(String.format("native method '%s' error:%s",nativeName, e.getMessage()));
		}

	}

}
